#include "QtBox2DUndoNode.h"
#include "QtBox2DScene.h"
#include "qtbox2dabstractitem.h"


void UndoNode_Normal::undo()
{
	if (mScene)
	{
		foreach(QString itemName, mItemNames)
		{
			QtBox2DBaseItem* boxItem = mScene->getItem(itemName);
			if (!boxItem)
			{
				continue;
			}

			//boxItem->disconnectManager();
			if (mItemProperty == "pos" && dynamic_cast<QtBox2DAbstractItem*>(boxItem))
			{
				boxItem->setPos(boxItem->pos() + mUndoValue.toPointF() - mRedoValue.toPointF());
			}
			else
			{
				boxItem->setProperty(mItemProperty, mUndoValue);
			}
			//boxItem->connectManager();
		}
	}
}

void UndoNode_Normal::redo()
{
	if (mScene)
	{
		foreach(QString itemName, mItemNames)
		{
			QtBox2DBaseItem* boxItem = mScene->getItem(itemName);
			if (!boxItem)
			{
				continue;
			}

			//boxItem->disconnectManager();
			if (mItemProperty == "pos" && dynamic_cast<QtBox2DAbstractItem*>(boxItem))
			{
				boxItem->setPos(boxItem->pos() + mRedoValue.toPointF() - mUndoValue.toPointF());
			}
			else
			{
				boxItem->setProperty(mItemProperty, mRedoValue);
			}
			//boxItem->connectManager();
		}
	}
}

//==================================

void UndoNode_Add::setItemNames(const QStringList& itemNames)
{
	mItemNames = itemNames;

	mBuffer.open(QBuffer::ReadWrite);
	QDataStream out(&mBuffer);

	for(int i=mItemNames.size()-1; i>=0; --i)
	{
		QString itemName = mItemNames.at(i);
		QtBox2DAbstractItem* boxItem = dynamic_cast<QtBox2DAbstractItem*>(mScene->getItem(itemName));
		if (boxItem)
		{
			out << *boxItem;
		}
	}
}

void UndoNode_Add::undo()
{
	mScene->deleteItems(mItemNames);
}

void UndoNode_Add::redo()
{
	mScene->clearSelection();

	QDataStream in(&mBuffer);
	mBuffer.open(QBuffer::ReadOnly);
	mScene->loadItemsFromDataStream(in, false);
}

//==========================================

void UndoNode_Remove::setItemNames(const QStringList& itemNames)
{
	mItemNames = itemNames;

	mBuffer.open(QBuffer::ReadWrite);
	QDataStream out(&mBuffer);

	for(int i=mItemNames.size()-1; i>=0; --i)
	{
		QString itemName = mItemNames.at(i);
		QtBox2DAbstractItem* boxItem = dynamic_cast<QtBox2DAbstractItem*>(mScene->getItem(itemName));
		if (boxItem)
		{
			out << *boxItem;
		}
	}
}

void UndoNode_Remove::undo()
{
	mScene->clearSelection();

	QDataStream in(&mBuffer);
	mBuffer.open(QBuffer::ReadOnly);
	mScene->loadItemsFromDataStream(in, false);
}

void UndoNode_Remove::redo()
{
	mScene->deleteItems(mItemNames);
}